package com.example.onlinemallsystem.service.impl;

import com.example.onlinemallsystem.entity.Cart;
import com.example.onlinemallsystem.entity.Order;
import com.example.onlinemallsystem.entity.Product;
import com.example.onlinemallsystem.entity.User;
import com.example.onlinemallsystem.mapper.OrderMapper;
import com.example.onlinemallsystem.mapper.ProductMapper;
import com.example.onlinemallsystem.mapper.UserMapper;
import com.example.onlinemallsystem.service.CartService;
import com.example.onlinemallsystem.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CartService cartService;

    @Override
    public int createOrder(Order order, String buyerName, Long productId, String sellerName) {
        return createOrder(order, buyerName, productId, sellerName, 1); // 默认数量为1
    }

    @Override
    public int createOrder(Order order, String buyerName, Long productId, String sellerName, Integer quantity) {
        User buyer = userMapper.findByUsername(buyerName);
        User seller = userMapper.findByUsername(sellerName);
        if (buyer == null || seller == null) {
            throw new RuntimeException("用户不存在，无法创建订单");
        }
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在，无法创建订单");
        }

        // 检查库存
        if (product.getStock() < quantity) {
            throw new RuntimeException("商品库存不足，无法创建订单");
        }

        // 设置订单信息
        order.setBuyerId(buyer.getId());
        order.setSellerId(seller.getId());
        order.setProductId(productId);
        order.setProductName(product.getName());

        // 计算总金额：单价 * 数量
        if (order.getTotalAmount() == null) {
            order.setTotalAmount(product.getPrice().multiply(BigDecimal.valueOf(quantity)));
        }

        order.setBuyerName(buyerName);
        order.setSellerName(sellerName);
        order.setReceiverAddress(buyer.getAddress());

        if (order.getTotalAmount() == null) {
            throw new RuntimeException("订单价格不能为空");
        }

        order.setReceiverName(buyer.getUsername());
        if (order.getReceiverName() == null || order.getReceiverName().isEmpty()) {
            throw new RuntimeException("收货人姓名不能为空");
        }

        order.setReceiverPhone(buyer.getPhone());
        if (order.getReceiverPhone() == null || order.getReceiverPhone().isEmpty()) {
            throw new RuntimeException("收货人电话不能为空");
        }

        order.setReceiverAddress(buyer.getAddress());
        if (order.getReceiverAddress() == null || order.getReceiverAddress().isEmpty()) {
            throw new RuntimeException("收货人地址不能为空");
        }

        order.setProductName(product.getName());
        if (order.getProductName() == null || order.getProductName().isEmpty()) {
            throw new RuntimeException("商品名不能为空");
        }

        order.setOrderNo("ORD" + System.currentTimeMillis());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setPayStatus(0); // 未支付
        order.setOrderStatus(0); // 待付款

        // 减少库存
        product.setStock(product.getStock() - quantity);
        productMapper.update(product);

        System.out.println("创建订单，buyerName=" + buyerName + ", sellerName=" + sellerName + ", quantity=" + quantity);
        return orderMapper.insert(order);
    }

    @Override
    public int cancelOrder(Long id) {
        return orderMapper.deleteById(id);
    }

    @Override
    public int updateOrder(Order order) {
        order.setUpdateTime(new Date());
        return orderMapper.update(order);
    }

    @Override
    public Order getOrderById(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public List<Order> getOrdersByBuyerId(Long buyerId) {
        return orderMapper.selectByBuyerId(buyerId);
    }

    @Override
    public List<Order> getOrdersBySellerId(Long sellerId) {
        return orderMapper.selectBySellerId(sellerId);
    }

    @Override
    public List<Order> getOrdersByStatusB(Long buyerId, Integer orderStatus) {
        Order order = new Order();
        order.setBuyerId(buyerId);
        order.setOrderStatus(orderStatus);
        return orderMapper.selectByStatusB(order);
    }

    @Override
    public List<Order> getOrdersByStatusS(Long sellerId, Integer orderStatus) {
        Order order = new Order();
        order.setSellerId(sellerId);
        order.setOrderStatus(orderStatus);
        return orderMapper.selectByStatusS(order);
    }

    @Override
    public Integer countOrders(Long userId, Integer orderStatus) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("orderStatus", orderStatus);
        return orderMapper.countOrders(params);
    }

    @Override
    public boolean existByOrderId(String orderId) {
        // 这里需要实现检查订单号是否存在的逻辑
        return false;
    }

    @Override
    public Integer getOrderStatus(Long id) {
        return orderMapper.getOrderStatus(id);
    }

    @Override
    @Transactional
    public Long createOrderFromCart(Long buyerId) {
        List<Cart> cartItems = cartService.listCartItems(buyerId);

        System.out.println("购物车商品数量: " + cartItems.size());
        if (cartItems.isEmpty()) {
            throw new RuntimeException("购物车为空，无法创建订单");
        }

        User buyer = userMapper.findById(buyerId);
        if (buyer == null) {
            throw new RuntimeException("买家不存在");
        }

        Long lastOrderId = null;

        for (Cart cartItem : cartItems) {
            Product product = productMapper.selectById(cartItem.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在，无法创建订单");
            }
            if (product.getStock() < cartItem.getQuantity()) {
                throw new RuntimeException("商品库存不足，无法创建订单");
            }

            User seller = userMapper.findById(product.getSellerId());
            if (seller == null) {
                throw new RuntimeException("卖家不存在，无法创建订单");
            }

            Order order = new Order();

            order.setBuyerId(buyerId);
            order.setSellerId(seller.getId());
            order.setProductId(product.getId());
            order.setProductName(product.getName());
            order.setTotalAmount(product.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())));
            order.setBuyerName(buyer.getUsername());
            order.setSellerName(seller.getUsername());
            order.setReceiverName(buyer.getUsername());
            order.setReceiverPhone(buyer.getPhone());
            order.setReceiverAddress(buyer.getAddress());
            order.setOrderNo("ORD" + System.currentTimeMillis() + (int)(Math.random()*1000));
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setPayStatus(0);
            order.setOrderStatus(0);

            int rows = orderMapper.insert(order);
            System.out.println("插入订单返回rows: " + rows + ", 订单号: " + order.getOrderNo());
            if (rows != 1) {
                throw new RuntimeException("订单创建失败");
            }
            lastOrderId = order.getId();

            product.setStock(product.getStock() - cartItem.getQuantity());
            productMapper.update(product);

            cartService.deleteCartItem(buyerId, cartItem.getProductId());
            System.out.println("已删除购物车项: " + cartItem.getProductId());
        }

        return lastOrderId;
    }

    @Override
    @Transactional
    public boolean simulatePayment(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在，无法支付");
        }
        if (order.getPayStatus() == 1) {
            throw new RuntimeException("订单已支付，无需重复支付");
        }

        // 模拟支付成功
        order.setPayStatus(1); // 已支付
        order.setPayTime(new Date());
        order.setOrderStatus(1); // 待发货

        int rows = orderMapper.update(order);
        return rows == 1;
    }

    @Override
    public List<Order> getAllOrders() {
        // 这里需要实现获取所有订单的逻辑
        // 暂时返回空列表，实际应该从数据库查询
        return orderMapper.selectAll();
    }

    @Override
    public List<Order> getOrdersBySellerName(String sellerName) {
        return null;
    }

    @Override
    public List<Order> getOrdersByBuyerName(String buyerName) {
        // 这里需要实现根据买家名称查询订单的逻辑
        // 暂时返回空列表，实际应该从数据库查询
        return orderMapper.selectByBuyerName(buyerName);
    }

    @Override
    public List<Order> searchOrdersByOrderNo(String orderNo) {
        // 这里需要实现根据订单号搜索订单的逻辑
        // 暂时返回空列表，实际应该从数据库查询
        return orderMapper.searchByOrderNo(orderNo);
    }

    @Override
    public List<Order> searchOrdersByProductName(String productName) {
        // 这里需要实现根据商品名称搜索订单的逻辑
        // 暂时返回空列表，实际应该从数据库查询
        return orderMapper.searchByProductName(productName);
    }
}